const router = require("koa-router")();
const Menu = require("../models/menusSchema");
const utils = require("../utils/utils");

router.prefix("/menu");

router.get("/list", async (ctx, next) => {
  const { menuName, menuState } = ctx.request.query;
  const params = {};
  if (menuName) params.menuName = { $regex: menuName };
  if (menuState) params.menuState = menuState;
  try {
    let res = await Menu.find(params);
    ctx.body = utils.success({ data: res });
  } catch (error) {
    ctx.body = utils.fail(error.stack);
  }
});
router.post("/operate", async (ctx) => {
  const { _id, dialogFormType, ...params } = ctx.request.body;
  try {
    if (dialogFormType == "Add") {
      let res = await Menu.findOne(
        { $or: [{ menuName: params.menuName }] },
        "_id menuName"
      );
      if (res) {
        ctx.body = utils.fail({
          data: null,
          code: 400,
          msg: "检测到有重复角色,请勿重复添加",
        });
      } else {
        let menu = new Menu({
          parentId:[...params.parentId],
          ...params
        });
        menu.save();
        ctx.body = utils.success({ data: null, msg: "添加成功", code: 200 });
      }
    } else if (dialogFormType == "Edit") {
      let res = await Menu.findByIdAndUpdate({ _id }, { parentId:[...params.parentId],...params });
      ctx.body = utils.success({ data: null, msg: "编辑成功", code: 200 });
    } else if (dialogFormType == "Del") {
      let res = await Menu.findByIdAndRemove({ _id }, { ...params });
      ctx.body = utils.success({ data: null, msg: "删除成功", code: 200 });
    }
  } catch (error) {
    ctx.body = utils.fail(error.stack);
  }
});
module.exports = router;
